package com.yilin.platform.base_core.interceptor;


import com.yilin.platform.base_core.application.AppUtil;
import com.yilin.platform.base_core.application.BaseCode;
import com.yilin.platform.base_core.application.UserUtil;
import com.yilin.platform.base_core.commons.annotation.SkipLoginVerify;
import com.yilin.platform.base_core.commons.utils.ArrayUtil;
import com.yilin.platform.base_core.commons.utils.JsonUtil;
import com.yilin.platform.base_core.commons.utils.constant.HttpConstant;
import com.yilin.platform.entity.enums.user.UserType;
import com.yilin.platform.entity.user.Account;
import com.yilin.platform.service.user.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微服务内部鉴权控制器
 */
@Configuration
public class LoginInterceptor implements  HandlerInterceptor  {
    private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Lazy
    @Autowired
    IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return responseErr(response, BaseCode.RES_NOT_EXIST, "请求的链接地址不存在");
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String customerIp = AppUtil.getIp(request);
        //#### 进行用户鉴权监控
        SkipLoginVerify skipLoginVerify = handlerMethod.getMethodAnnotation(SkipLoginVerify.class);
        if (skipLoginVerify != null) return true;
        String requestToken = request.getHeader(HttpConstant.TOKEN);
        Account loginUser = UserUtil.getLoginUser(requestToken);
        boolean mobile = request.getHeader(HttpConstant.MOBILE)!=null;
        //if (loginUser!=null) saveLog(loginUser, mobile, customerIp, request.getRequestURI());
        //### 操作刷新保存 移动端就不要设置啦
        if(!mobile) UserUtil.updateTokenAccessTime(requestToken);
        return true;
    }


    //返回前台数据
    private boolean responseErr(HttpServletResponse response, Integer code, String msg) {
        try {
            Map<String, Object> returnData = new HashMap<>();
            response.setCharacterEncoding("UTF-8");//设置字符集为'UTF-8'
            response.setContentType("application/json");//设置格式为text/json 
            returnData.put("success", false);
            returnData.put("msg", msg);
            returnData.put("code", code);
            PrintWriter write = response.getWriter();
            write.write(JsonUtil.objectToJson(returnData));
            write.flush();
            write.close();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    private List<String> userTypeNameList(List<UserType> userTypes) {
        return ArrayUtil.fieldAdd(userTypes, obj -> obj.name);
    }

}
